package org.sippr.utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.net.HttpURLConnection;
import java.net.URL;

@Component
public class EEPUtil {


    //依赖yml文件注入配置，静态的要这样写
    @Getter
    public static String URL;

    @Value("${eep.server.url}")
    public void setUrl(String url) {
        URL = url;
    }


    //EEP获取通过账户密码获取用户数据，如果是空，就登录失败
    public static JsonNode getUser(String account, String password) {

        try {
            URL apiUrl = new URL(URL + "/api/DataFromEepApi/GetUserByPassword?Account=" + Base64Util.Encode(account) + "&password=" + Base64Util.Encode(password));

            HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();
            connection.setRequestMethod("GET");
            int responseCode = connection.getResponseCode();
            if (responseCode != 200) {
                System.out.println("EEP服务器异常！");
                return null;
            }

            ObjectMapper mapper = new ObjectMapper();
            JsonNode rootNode = mapper.readTree(connection.getInputStream());
            String code = rootNode.get("Code").asText();
            if (!code.equals("0")) {
                System.out.println("未从EEP获取到用户数据！");
                return null;
            }
            return rootNode.get("Data");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}
